<?php
// 后台用户模块
namespace Admin\Controller;
use Admin\Model\EmailListModel;
use Admin\Model\UserModel;

class UserController extends CommonController {
	public function _filter(&$map){
		 $map['id'] = array('egt',2);
		 if ($_REQUEST['account']){
		 	$map['account'] = array('like',"%".$_REQUEST['account']."%");
		 }
		
	}


    public function _before_index() {
        $this->assign('emailSuffix',getEmailSuffix());

    }

    public function edit() {
        $model = M ( CONTROLLER_NAME );
        $id = $_REQUEST [$model->getPk ()];
        $vo = $model->getById ( $id );
        $this->assign ( 'vo', $vo );

        $this->assign('emailSuffix',getEmailSuffix());
        $maillist = new EmailListModel();
        $this->assign('emaillist',$maillist->getMailListByUserId($id));
        $this->display();
    }

	public function add(){
		$Post = D("Post");
		$rs = $Post->where("post_status = 1")->select();
		$str = '';
		if(is_array($rs) && count($rs)>0){
			
			foreach ($rs as $key=>$val){
				$str .='<option value="'.$val['id'].'">'.$val['post_name'].'</option>';
			}
		}
		$this->assign("post_list",$str);
		$this->display("add");
	}
	// 检查帐号
	public function checkAccount() {
        // if(!preg_match('/^[a-z]\w{4,}$/i',$_POST['account'])) {
        //     $this->error( '用户名必须是字母，且5位以上！');
        // }
		$User = M("User");
        // 检测用户名是否冲突
        $name  =  $_REQUEST['account'];
        $result  =  $User->getByAccount($name);
        if($result) {
        	$this->error('该用户名已经存在！');
        }else {
           	$this->success('该用户名可以使用！');
        }
    }
    
	// 插入数据
	public function insert() {
		// 创建数据对象
		$User	 =	 D("User");
		if(!$User->create()) {
			$this->error($User->getError(),"__URL__",true);
		}else{
			// 写入帐号数据
            $data = $_REQUEST;
			if($result	 =	 $User->add()) {
				$this->addRole($result);
                $main_email = $this->addEmailList($result);
                if ($main_email) {
                    D("User")->where('id='.$result)->save(array('email'=>$main_email));
                }
                if (!empty($data['account'])) {
                    Vendor('C6.Api');
                    $c6 =   new \Api();
                    $userId = $c6->findUserIdByUserName($data['account']);
                    $model = M('User')->getById($result);
                    $model['user_id'] = $userId;
                    M('User')->save($model);
                }
				$this->success('用户添加成功！',"__URL__",true);
			}else{

				$this->error('用户添加失败！',"__URL__",true);
			}
		}
	}

    public function update() {
        $model = D ( CONTROLLER_NAME );
        if (false === $model->create ()) {
            $this->error ( $model->getError () );
        }
//        if ($_REQUEST['email'] != array_unique($_REQUEST['email'])){
//            $this->error('保存失败!重复邮箱');
//        }
        $result = $this->addEmailList();

        if ($result) {
            $model->email = $result;
        }
        // 更新数据
        $list=$model->save ();
        if (false !== $list) {
            //成功提示
            //$this->assign ( 'jumpUrl', Cookie::get ( '_currentUrl_' ) );
            $this->success ('编辑成功!');
        } else {
            //错误提示
            $this->error ('编辑失败!');
        }

    }

    /**
     * 保存邮件列表  返回主邮箱
     * @return bool|string
     */
    public function addEmailList($user_id = '') {

        $maillist = new EmailListModel();
        $user_id = $_REQUEST['id']?$_REQUEST['id']:$user_id;
        $mainEmail = '';
        if (count($_REQUEST['email']) && count($_REQUEST['mailbox_suffix'])  && count($_REQUEST['is_main'])){
            $hasemail = false;
            foreach ($_REQUEST['email'] as $key => $item) {
                if ($maillist->hasEmail($item.getEmailSuffix(true,$_REQUEST['mailbox_suffix'][$key]),$user_id)) {
                    $hasemail = true;
                }
                if ($_REQUEST['is_main'][$key]) {
                    $mainEmail   = $_REQUEST['email'][$key].getEmailSuffix(true,$_REQUEST['mailbox_suffix'][$key]);
                }
            }
            if ($hasemail){
                $this->error('保存失败!该邮箱已经被绑定');
            }
            if ($maillist->saveMailList($_REQUEST['email'],$_REQUEST['mailbox_suffix'],$_REQUEST['is_main'],$user_id) === false){
                $this->error('保存失败!'.$maillist->getDbError());
            }
            return $mainEmail;
        }
        return false;
    }

	protected function addRole($userId) {
		//新增用户自动加入相应权限组
		$RoleUser = M("RoleUser");
		$RoleUser->user_id	=	$userId;
        // 默认加入网站编辑组
        $RoleUser->role_id	=	3;
		$RoleUser->add();
	}

    //重置密码
    public function resetPwd()
    {
    	$id  =  $_POST['id'];
        $password = $_POST['password'];
        if(''== trim($password)) {
        	$this->error('密码不能为空！');
        }
        $User = M('User');
		$User->password	=	md5($password);
		$User->id			=	$id;
		$result	=	$User->save();
        if(false !== $result) {
            $this->success("密码修改为$password");
        }else {
        	$this->error('重置密码失败！');
        }
    }
    
    //递归查询部门档案信息
    public function getDeptList($parent_id = 0){
    	$dept = D("Department");
    	$list = $dept->where("parent_id = ".$parent_id)->order("id")->select();
    	if(is_array($list) && count($list)>0){
    		foreach ($list as $key=>$val){
    			$rs_child = $dept->where("parent_id = ".$val['id'])->order("id")->select();
    			if(is_array($rs_child) && count($rs_child)>0){
    				$list[$key]['child_dept_list'] = $this->getDeptList($val['id']);
    				$list[$key]['child_num'] = count($this->getDeptList($val['id']));
    			}else{
    				$list[$key]['child_num'] = 0;
    			}
    		}
    	}
    
    	return $list;
    }

    //将这棵树展示在页面上,供选择上级部门使用
    public function showDeptListByUpDept($list){
    	if(is_array($list) && count($list)>0){
    		$str = '';
    		foreach ($list as $key=>$val){
    			$id = $val['id'];
    			$dept_name = $val['dept_name'];
    
    			$str .='<li><a id="tree_'.$id.'" onclick="getUpDept('.$id.','."'$dept_name'".')">'.$dept_name.'</a>';
    			if($val['child_num']>0){
    				$str .='<ul>';
    				$str .= $this->showDeptListByUpDept($val['child_dept_list']);
    				$str .="</ul>";
    			}
    			$str .='</li>';
    		}
    
    		return $str;
    	}
    }
    
    
    //点击选择部门
    public function tree(){
    	$dept = D("Department");
    	$dept_tree = $this->showDeptListByUpDept($this->getDeptList());
    	$this->assign("dept_tree",$dept_tree);
    	$this->display("tree");
    }


    public function readerXmlFile() {

        $file = $_SERVER['DOCUMENT_ROOT'].'one/Public/yuntu.xlsx';

        $data = readExcel($file);
        $data  = $data[0]['Content'];
        $model = new UserModel();
        foreach ($data as $key => $item) {
            if ($key != 1) {
               $item = explode('@',$item[1]);
               $model->changeUserEmailByName($item[0],'@'.$item[1]);
            }
        }

    }

    /**
     * 重写 多选删除 需要删除email list 上的帐号
     */
    public function multiDelete() {
        $model = M (CONTROLLER_NAME);
        if (! empty ( $model )) {
            $pk = $model->getPk ();
            $ids = $_REQUEST ['ids'];
            if (isset ( $ids )) {
                $condition = array ($pk => array ('in', explode ( ',', $ids ) ) );
                $where = array ('user_id' => array ('in', explode ( ',', $ids ) ) );
                $list=$model->where ( $condition )->delete();
                $dfalg=D('email_list')->where ( $where )->delete();
                if ($list!==false && $dfalg !== false) {
                    $this->success ('删除成功！','',true );
                } else {
                    $this->error ('删除失败！','',true);
                }
            } else {
                $this->error ( '非法操作','',true );
            }
        }
    }


 	
}
?>